package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dtos.PageResult;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.threadlocal.UserThreadLocalUtils;
import com.heima.file.service.MinioService;
import com.heima.model.media.dtos.WmMaterialDto;
import com.heima.wemedia.config.WebMvcConfig;
import com.heima.wemedia.entity.WmMaterial;
import com.heima.wemedia.entity.WmNewsMaterial;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.wemedia.service.WmNewsMaterialService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.ws.Response;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2022-10-19
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private MinioService minioService;
    @Autowired
    private WmMaterialService materialService;

    @Autowired
    private WmNewsMaterialService newsMaterialService;

    @Override
    public String upload(MultipartFile multipartFile) {
        Integer userId = UserThreadLocalUtils.getUserId();
//        if (userId == null || userId == 0) {
//            log.error("用户信息不存在");
//            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
//        }
//        获取文章的原名字
        String originalFilename = multipartFile.getOriginalFilename();
//        获取后缀
        String suffix = StringUtils.substringAfterLast(originalFilename, ".");
//         新文件名
        String newFileName = UUID.randomUUID().toString() + "." + suffix;
//        上传到minio
        try {
            String url = minioService.uploadImgFile(null, newFileName, multipartFile.getInputStream());
//        把数据保存数据库
            WmMaterial material = new WmMaterial();
            material.setUserId(userId);
            material.setUrl(url);
            material.setType(0);
            material.setIsCollection(false);
            material.setCreatedTime(new Date());
            boolean b = save(material);
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
    }


    @Override
    public PageResult<WmMaterial> findByPage(WmMaterialDto dto) {
//        Integer userId = UserThreadLocalUtils.getUserId();
//        if (userId == null) {
//            log.error("用户民不存在niaidiaiwnd");
//            throw new LeadException(AppHttpCodeEnum.AD_USER_NOT_EXIST);
//        }
        Page<WmMaterial> iPage = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmMaterial> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dto.getIsCollection() == 1, WmMaterial::getIsCollection, dto.getIsCollection());
//        lqw.eq(WmMaterial::getUserId, userId);
        IPage<WmMaterial> page = page(iPage, lqw);

        return new PageResult<>(dto.getPage(), dto.getSize(), page.getTotal(), page.getRecords());
    }

    @Override
    public void deleteById(Integer id) {
//        Integer userId = UserThreadLocalUtils.getUserId();
//        if (userId == null) {
//            log.error("用户民不存在4654654");
//            throw new LeadException(AppHttpCodeEnum.AD_USER_NOT_EXIST);
//        }
        LambdaQueryWrapper<WmNewsMaterial> lqw = new LambdaQueryWrapper<>();
        lqw.eq(WmNewsMaterial::getMaterialId, id);
        int count = newsMaterialService.count(lqw);
        if (count > 0) {
            log.error("素材被应用无法删除");
            throw new LeadException(AppHttpCodeEnum.CAN_NOT_DELETE);
        }
        LambdaQueryWrapper<WmMaterial> lq = new LambdaQueryWrapper<>();
//        lq.eq(WmMaterial::getUserId, userId).eq(WmMaterial::getId, id);
        WmMaterial one = getOne(lq);
        if(Objects.isNull(one)){
            log.error("素材不存在");
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String url = one.getUrl();

        boolean b = removeById(id);
        if (b != true) {
            log.error("数据不存在无法删除");
            throw new LeadException(AppHttpCodeEnum.CAN_NOT_DELETE);
        }

        minioService.delete(url);
    }
}
